<?php

namespace api\energy\common;

use ReflectionClass;

abstract class Request
{
    private $headers = [];
    private $method = '';
    private $url = '';
    private $requestData = [];

    public function execute()
    {
        try {
            $reflectionClass = new ReflectionClass($this);
        } catch (\ReflectionException $e) {
        }
        $build = $reflectionClass->getMethod("build");
        $build->invoke($this);

        return Http::doCommHttp($this->method, $this->url, $this->requestData, $this->headers);
    }

    /**
     * @return string
     */
    protected function getUrl()
    {
        return $this->url;
    }

    /**
     * @param $url
     */
    protected function setUrl($url)
    {
        $this->url = $url;
    }

    /**
     * @return string
     */
    protected function getMethod()
    {
        return $this->method;
    }

    /**
     * @param $method
     */
    protected function setMethod($method)
    {
        $this->method = $method;
    }

    /**
     *
     * @param $key
     * @return array|mixed|string
     */
    protected function getRequestData($key = '')
    {
        if ($key) {
            return $this->requestData[$key] ?? '';
        } else {
            return $this->requestData;
        }
    }

    /**
     *
     * @param $name
     * @param $value
     */
    protected function setRequestData($name, $value = '')
    {
        if (is_array($name)) {
            $this->requestData = $name;
        } else {
            $this->requestData[$name] = $value;
        }
    }


    /**
     * @return array
     */
    protected function getHeaders()
    {
        return $this->headers;
    }

    /**
     * @param $headers
     */
    protected function setHeaders($headers)
    {
        $this->headers = $headers;
    }

    public function __call($method, $parameters)
    {
        // 设置数据
        if (substr($method, 0, 3) == 'set') {
            $paramKey = substr($method, 3);

            $paramKey = lcfirst($paramKey);
            $this->requestData[$paramKey] = $parameters[0] ?? '';
        }
        // 获取数据
        if (substr($method, 0, 3) == 'get') {
            $paramKey = substr($method, 3);

            $paramKey = lcfirst($paramKey);
            return $this->requestData[$paramKey] ?? '';
        }

        return $this;
    }

    abstract function build();


}